package com.sinovatio.tls.zttbg.webPage.controller;


import com.google.common.collect.Maps;
import com.sinovatio.tls.zttbg.constants.ServiceRoutesPathConstant;
import com.sinovatio.tls.zttbg.webPage.controller.service.TestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;


/**
 * Created with IntelliJ IDEA.
 * User: lhl
 * Date: 2017/09/20
 * Time: 15:46
 */
@Controller
@RequestMapping(value = "/admin")
public class IndexController {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    TestService testService;

    @Autowired
    LoadBalancerClient loadBalancer;

    private static Logger LOG = LoggerFactory.getLogger(IndexController.class);

    @GetMapping
    public ModelAndView index(){
        return new ModelAndView("index");
    }

    @GetMapping(value = "/index")
    public ModelAndView indexContent(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        // http://gate/serviceAccompany/accompany/testData
//        String url = "http://service-accompany/accompany/testData";

        String url = ServiceRoutesPathConstant.SERVICEACCOMPANYTESTPATH;

        ServiceInstance instance = this.loadBalancer.choose("gate");
        LOG.info("当前访问的gate服务端口："+instance.getPort());
        Map<String,Object> map = Maps.newHashMap();
        Integer i = 1;
        map.put("test",i);
        url = url+"?test={test}";
        System.out.println("请求地址:" + url);
        String response = restTemplate.getForObject(url,String.class,map);
        modelAndView.addObject("value",response);
        return modelAndView;
    }


    @GetMapping(value = "/error/500")
    public ModelAndView error(){
        return new ModelAndView("/error/500");
    }

    @GetMapping(value = "/error/403")
    @ResponseBody
    public String permissionDecline(){
        return "权限不足";
    }

    @PostMapping(value = "/testPage")
    @ResponseBody
    public String testPaginatorData(Integer pageNum, Integer pageSize) {
        LOG.info("pageNum={},pageSize={}", pageNum, pageSize);
        return testService.getPaginatiorData(pageNum, pageSize);
    }

    /**
     * 分页demo页面
     * @return
     */
    @GetMapping(value = "/paginator")
    public ModelAndView paginator(){
        return new ModelAndView("paginator/paginator_demo");
    }
}
